package com.nutransit;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;

import com.google.android.gms.maps.model.LatLng;
import com.mylibrary.mylibrary.parsing.AsyncTaskInterface;
import com.mylibrary.mylibrary.parsing.AsyncTaskUtility;
import com.mylibrary.mylibrary.util.CommonCode;
import com.nutransit.commoncode.Webservice_parametrs;
import com.nutransit.map.DirectionsJSONParser;

public class Fragment_Cab_Route_selection extends Fragment implements Webservice_parametrs
{
	String url;
	private static final String TAG_RESULT = "predictions";
	JSONObject json;
	private Context context;
	JSONArray contacts = null;
	AutoCompleteTextView et_current_location, et_destination_location;
	ArrayList<String> names;
	ArrayAdapter<String> adp;
	String browserKey = "AIzaSyCRAuue19AqZYuFHz4Uo_sYgEj9VOFlHVM";

	private View rootview;
	
	private double source_lat,source_lon,destination_lat,destination_lon;
	private boolean flag_get_lat_lon = true;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		rootview = inflater.inflate(R.layout.fragment_select_source_destination, container, false);
		init_var();
		return rootview;
	}

	private void init_var()
	{
		context = getActivity();
		
		et_current_location = (AutoCompleteTextView) rootview.findViewById(R.id.et_current_location);
		et_current_location.setThreshold(0);
		et_destination_location = (AutoCompleteTextView) rootview.findViewById(R.id.et_destination_location);
		rootview.findViewById(R.id.btn_find_nu_cab).setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				if(et_current_location.getText().toString().trim().length()<1)
					CommonCode.showMessage(getString(R.string.Please_enter_the_First_Name), context);
				if(et_destination_location.getText().toString().trim().length()<1)
					CommonCode.showMessage(getString(R.string.Please_enter_the_destination_address), context);
				else
					get_Lat_Long();
			}
		});;
		et_destination_location.setThreshold(0);
		names = new ArrayList<String>();

		et_current_location.addTextChangedListener(new TextWatcher()
		{
			public void afterTextChanged(Editable s) { }
			public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
				find_address_suggesstio(et_current_location);
			}
		});

		et_destination_location.addTextChangedListener(new TextWatcher()
		{
			public void afterTextChanged(Editable s) { }
			public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
				find_address_suggesstio(et_destination_location);
			}
		});
	}

	protected void get_Lat_Long()
	{
		String uri = null;
		try
		{
			if(flag_get_lat_lon == true){
				uri = "http://maps.google.com/maps/api/geocode/json?address=" + URLEncoder.encode(et_current_location.getText().toString().trim(), "UTF-8") + "&sensor=false";
			}else {
				uri = "http://maps.google.com/maps/api/geocode/json?address=" + URLEncoder.encode(et_destination_location.getText().toString().trim(), "UTF-8") + "&sensor=false";
			}
			new AsyncTaskUtility(context, null, uri).getJSONResponse(new AsyncTaskInterface()
			{
				@Override
				public void getJSONObjectFromAsynkTask(JSONObject json)
				{
					try
					{
						if(json!=null)
						{
							if(json.has("results") && json.getJSONArray("results").length()>0)
							{
								JSONObject jsonObject = json.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location");
								Double lng = jsonObject.getDouble("lng");
								Double lat = jsonObject.getDouble("lat");
								
								if(flag_get_lat_lon == true){
									source_lat = lat;
									source_lon = lng;
									flag_get_lat_lon = false;
									get_Lat_Long();
								}else {
									destination_lat = lat;
									destination_lon = lng;
									flag_get_lat_lon = true;
									
									get_source_destination_cost_calculation(source_lat,source_lon,destination_lat,destination_lon);
								}
								
								System.out.println("Lat lon :"+"Source :"+source_lat+" "+source_lon+" Destination :"+destination_lat+" "+destination_lon);
								
							}
						}
					}
					catch (JSONException e)
					{
						e.printStackTrace();
					}
				}
			});
		}
		catch (UnsupportedEncodingException e1)
		{
			e1.printStackTrace();
		}
	}

	protected void get_source_destination_cost_calculation(double source_lat2, double source_lon2, double destination_lat2, double destination_lon2)
	{
		// Getting URL to the Google Directions API
		String url = getDirectionsUrl(new LatLng(source_lat2, source_lon2), new LatLng(destination_lat2, destination_lon2));

		DownloadTask downloadTask = new DownloadTask();
		// Start downloading json data from Google Directions API
		downloadTask.execute(url);
		
	}

	public void find_address_suggesstio(final AutoCompleteTextView et_location_pass)
	{
		try
		{
			String[] search_text = et_location_pass.getText().toString().split(",");
			url = URL_GOOGLE_GET_PLACES + "?input=" + URLEncoder.encode(search_text[0], "utf-8") + "&sensor=true&key=" + browserKey;

			if (search_text.length <= 1)
			{
				names = new ArrayList<String>();
				new AsyncTaskUtility(context, null, url, false).getJSONResponse(new AsyncTaskInterface()
				{
					@Override
					public void getJSONObjectFromAsynkTask(JSONObject json)
					{
						try
						{
							if (json != null)
							{
								contacts = json.getJSONArray(TAG_RESULT);
								for (int i = 0; i < contacts.length(); i++)
								{
									names.add(contacts.getJSONObject(i).getString("description"));
								}
								adp = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, names)
								{
									@Override
									public View getView(int position, View convertView, ViewGroup parent)
									{
										View view = super.getView(position, convertView, parent);
										TextView text = (TextView) view.findViewById(android.R.id.text1);
										text.setTextColor(Color.BLACK);
										return view;
									}
								};
								et_location_pass.setAdapter(adp);
							}
						}
						catch (JSONException e)
						{
							e.printStackTrace();
						}
					}
				});
			}
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
	}
	
	private String getDirectionsUrl(LatLng origin, LatLng dest)
	{

		// Origin of route
		String str_origin = "origin=" + origin.latitude + "," + origin.longitude;

		// Destination of route
		String str_dest = "destination=" + dest.latitude + "," + dest.longitude;

		// Sensor enabled
		String sensor = "sensor=false";

		// Waypoints
		String waypoints = "";

		// Building the parameters to the web service
		String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + waypoints;

		// Output format
		String output = "json";

		// Building the url to the web service
		String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;

		return url;
	}
	
	// Fetches data from url passed
			private class DownloadTask extends AsyncTask<String, Void, String>
			{

				// Downloading data in non-ui thread
				@Override
				protected String doInBackground(String... url)
				{

					// For storing data from web service
					String data = "";

					try
					{
						// Fetching the data from web service
						data = downloadUrl(url[0]);
					}
					catch (Exception e)
					{
					}
					return data;
				}

				// Executes in UI thread, after the execution of
				// doInBackground()
				@Override
				protected void onPostExecute(String result)
				{
					super.onPostExecute(result);

					ParserTask parserTask = new ParserTask();

					// Invokes the thread for parsing the JSON data
					parserTask.execute(result);

				}
			}
			
			/** A method to download json data from url */
			private String downloadUrl(String strUrl) throws IOException
			{
				String data = "";
				InputStream iStream = null;
				HttpURLConnection urlConnection = null;
				try
				{
					URL url = new URL(strUrl);

					// Creating an http connection to communicate with url
					urlConnection = (HttpURLConnection) url.openConnection();

					// Connecting to url
					urlConnection.connect();

					// Reading data from url
					iStream = urlConnection.getInputStream();

					BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

					StringBuffer sb = new StringBuffer();

					String line = "";
					while ((line = br.readLine()) != null)
					{
						sb.append(line);
					}

					data = sb.toString();

					br.close();

				}
				catch (Exception e)
				{
				}
				finally
				{
					iStream.close();
					urlConnection.disconnect();
				}
				return data;
			}
			
			/** A class to parse the Google Places in JSON format */
			private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>>
			{
				double distance_calculate_cost;

				// Parsing the data in non-ui thread
				@Override
				protected List<List<HashMap<String, String>>> doInBackground(String... jsonData)
				{

					JSONObject jObject;
					List<List<HashMap<String, String>>> routes = null;

					try
					{
						jObject = new JSONObject(jsonData[0]);
						DirectionsJSONParser parser = new DirectionsJSONParser();

						// Starts parsing data
						routes = parser.parse(jObject);
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
					return routes;
				}

				// Executes in UI thread, after the parsing process
				@Override
				protected void onPostExecute(List<List<HashMap<String, String>>> result)
				{

					ArrayList<LatLng> points = null;
					String distance = "",  duration = "";
					System.out.println("Result of parsing :" + result);

					// Traversing through all the routes
					for (int i = 0; i < result.size(); i++)
					{
						points = new ArrayList<LatLng>();

						// Fetching i-th route
						List<HashMap<String, String>> path = result.get(i);

						// Fetching all the points in i-th route
						for (int j = 0; j < path.size(); j++)
						{
							HashMap<String, String> point = path.get(j);
							if (j == 0)
							{ // Get distance from the list
								distance = (String) point.get("distance");
								continue;
							}
							else if (j == 1)
							{ // Get duration from the list
								duration = (String) point.get("duration");
								continue;
							}

							double lat = Double.parseDouble(point.get("lat"));
							double lng = Double.parseDouble(point.get("lng"));
							LatLng position = new LatLng(lat, lng);
							points.add(position);
						}
						distance = distance.replaceAll(" km", "");
						double distance_calculate = (Double.parseDouble(distance) * 0.621371);
						distance_calculate_cost = (distance_calculate * 3);
						System.out.println("Distance location : " + distance_calculate+" Price :"+distance_calculate_cost);
					}
					
					Bundle bundle = new Bundle();
					bundle.putString(TAG_lat_source, source_lat+"");
					bundle.putString(TAG_long_source, source_lon+"");
					bundle.putString(TAG_lat_destination, destination_lat+"");
					bundle.putString(TAG_long_destination, destination_lon+"");
					bundle.putString(TAG_source, et_current_location.getText().toString().trim()+"");
					bundle.putString(TAG_destination, et_destination_location.getText().toString().trim()+"");
					bundle.putString(TAG_price, distance_calculate_cost+"");
					Fragment_Cab_Driver_List fragment_Cab_Driver_List = new Fragment_Cab_Driver_List();
					fragment_Cab_Driver_List.setArguments(bundle);
					final FragmentTransaction ft = getFragmentManager().beginTransaction();
					ft.add(R.id.fLayout_Container, fragment_Cab_Driver_List, "MyFragmentTag");
					ft.addToBackStack(null);
					ft.commit();
				}
			}
}
